#pragma once
#include "CWindow/CWindowBase.h"
#include "Win32Utils/CStrUtils.h"
#include <vector>
#include "CBitmapDraw.h"
#include <thread>
#include <condition_variable>
#include <mutex>

class CWindowPalette:
    public CWindowBase
{
public:
    CWindowPalette();
    ~CWindowPalette();

    wnd_msg LRESULT OnCreate(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnClose(WPARAM wParam, LPARAM lParam);

    wnd_msg LRESULT OnSize(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnGetMinMaxInfo(WPARAM wParam, LPARAM lParam);

    wnd_msg LRESULT OnEraseBkgnd(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnPaint(WPARAM wParam, LPARAM lParam);

    wnd_msg LRESULT OnLButtonDown(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnLButtonUp(WPARAM wParam, LPARAM lParam);
    wnd_msg LRESULT OnMouseMove(WPARAM wParam, LPARAM lParam);

    void SetNotifyWnd(HWND hWnd);
    void NotifyMessage(UINT uMsg, WPARAM wParam, LPARAM lParam);

    LPCBYTE GetPaletteData();
    void SetPaletteData(LPCBYTE lpData);
    DWORD GetPaletteIndex();
    void SetPaletteIndex(DWORD dwIndex);

private:

    DECLARE_WND_MESSAGE_MAP()


    void UpdateView();
    void DrawPalette();
    bool GetPaletteHit(int xPos, int yPos, POINT ptSize, POINT& ptHit);
    bool GetBkgPaletteHit(int xPos, int yPos, POINT ptSize, POINT& ptHit);
    DWORD GetReverseColor(DWORD dwColor);

    void DrawBitmap();
    void DrawTask();

private:

    BYTE m_BkgPalette[0x10] =
    {
        0x0F,0x2A,0x12,0x3C,0x0F,0x21,0x21,0x21,0x0F,0x27,0x22,0x22,0x0F,0x22,0x22,0x22
    };

    HDC         m_hMemDC = NULL;
    HBITMAP     m_hMemBitmap = NULL;

    HDC         m_hBackDC = NULL;
    HBITMAP     m_hBackBitmap = NULL;

    POINT       m_ptCurColorIndex = { 0, 0 };
    DWORD       m_nCurPaletteIndex = 1;

    LONG m_MinWidth = 64;
    LONG m_MinHeight = 64;

    HWND        m_NotifyWnd;

    bool        m_bLButtonDown = false;
    bool        m_bQuit = false;

    std::thread m_drawTask;
    std::mutex m_lockDraw;
    std::mutex m_lockDC;
    std::condition_variable m_cv;
};

